import axios from 'axios';

export const BASEURL = 'https://www.hudongmiao.com/';
// export const BASEURL = 'https://wwwstage.hudongmiao.com/';
// export const BASEURL = 'http://192.168.66.103:8081/haimiao-mp/';
/* eslint-disable */
const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API,
    headers: {
        token: localStorage.getItem('token'),
    },
    timeout: 20000,
});

/* 过滤请求 */
service.interceptors.request.use((config) => {
    // 生产环境 移除 请求页面提示
    if (config.data && config.data.request_from_page && process.env.NODE_ENV !== 'development') {
        delete config.data.request_from_page;
    }
    console.log(config);
    return config;
});

/* 过滤响应 */
service.interceptors.response.use((result) => {
    if (result.data.message === '401') {
        // window.localStorage.removeItem('token');
        window.localStorage.clear();
        window.location.href = window.location.origin || 'https://www.hudongmiao.com/';

        console.log('登录过期');
        // TODO 处理登陆过期
        return Promise.reject('401');
    }
    if (result.status !== 200 || result.data.success === false) {
        return Promise.reject(result.data.message);
    }
    return result.data;
}, (err) => {
    return Promise.reject(err);
});

export const setToken = (token) => {
    service.defaults.headers.token = token || localStorage.getItem('token');
};

export default service;